/**
 * @file select
 * @author liaoxuezhi@baidu.com
 *
 * https://github.com/JedWatson/react-select
 */
/* eslint fecs-indent: [0, "space", 2, 2] */

import * as React from 'react';
import {
  PureComponent,
  PropTypes
} from 'react';
import {Renderer, filter} from '../../renderer';
import * as assign from 'object-assign';
import * as cx from 'classnames';
import Uplader from '../../../widgets/uploader/file';
import {Enhance as FormItem} from '../form-item';

@FormItem({
  type: 'file',
  validate() {
    const input = this.input;

    if (input && input.state.locked && this.isFormSubmitted()) {
      return `文件处理中，请稍候`;
    }

    if (input && input.state.onFormItemValid) {
      let fn = input.state.onFormItemValid;
      input.setState({
        onFormItemValid: null,
      }, () => setTimeout(fn, 600));
    }

    return true;
  },
  validateSchema: 'http://amis.baidu.com/schemas/form.json#/definitions/formItem'
})
export default class ImageUploader extends PureComponent {
  static propTypes = {
    className: PropTypes.string,
    formMode: PropTypes.string,
    formHorizontal: PropTypes.object
  };

  static defaultProps = {
    value: '',
    placeholder: '',
    btnLabel: '请选择文件',
    reciever: '/api/file',
    fileField: 'file',
    joinValues: true,
    delimiter: ',',
    downloadUrl: '', // '/api/file/'
    useChunk: 'auto',
    chunkSize: 5 * 1024 * 1024, // 文件大于5M， 自动分块上传
    startChunkApi: '/api/upload/startChunk',
    chunkApi: '/api/upload/chunk',
    finishChunkApi: '/api/upload/finishChunk',
    accept: 'text/plain',
    multiple: false,
    autoUpload: true,
    hideUploadButton: false
  };

  constructor(props) {
    super(props);
    this.changeValue = this.changeValue.bind(this);
    this.handleLock = this.handleLock.bind(this);
    this.handleUnLock = this.handleUnLock.bind(this);

    this.state = {
      locked: false,
      files: this.value2files(props.formItemValue, props)
    };
  }

  componentWillReceiveProps(nextProps) {
    const props = this.props;

    if (props.formItemValue !== nextProps.formItemValue) {
      this.setState({
        files: this.value2files(nextProps.formItemValue, nextProps)
      });
    }
  }

  value2files(value, props) {
    const {joinValues, multiple, delimiter} = props;

    if (multiple && joinValues && typeof value === 'string') {
      value = value.split(delimiter);
    }

    return value;
  }

  onSubmit(model, component, form) {
    const input = this;

    if (input.state.locked) {
      form.validate(component);

      if (input.state.unlockFn) {
        let fn = input.state.unlockFn;
        input.setState({
          unlockFn: null,
          onFormItemValid: () => form.submit()
        }, () => fn((error) => error || setTimeout(form.submit, 200)));
      }

      return false;
    }
  }

  changeValue(newValue) {
    const {
      joinValues,
      delimiter,
      multiple
    } = this.props;

    if (joinValues) {
      if (multiple) {
        newValue = newValue && newValue.map(item => item.value).join(delimiter);
      } else {
        newValue = newValue && newValue.value;
      }
    }

    this.props.setValue(newValue);
  }

  handleLock(unlockFn) {
    this.setState({locked: true, validateFlag: true, unlockFn});
  }

  handleUnLock() {
    this.setState({locked: false, unlockFn: null});
  }

  render() {
    const {
      name,
      placeholder,
      btnLabel,
      multiple,
      autoUpload,
      disabled,
      reciever,
      fileField,
      downloadUrl,
      data,
      maxSize,
      joinValues,
      delimiter,
      maxLength,

      useChunk,
      chunkSize,
      startChunkApi,
      chunkApi,
      finishChunkApi,
      accept,
      hideUploadButton
    } = this.props;


    const selectProps = {
      name,
      placeholder,
      btnLabel,
      multiple,
      autoUpload,
      value: this.state.files,
      onChange: this.changeValue,
      disabled,
      fileField,
      maxSize,
      reciever: filter(reciever, data),
      downloadUrl: filter(downloadUrl, data),
      onRequestLock: this.handleLock,
      onRequestUnLock: this.handleUnLock,

      joinValues,
      delimiter,
      maxLength,
      useChunk,
      chunkSize,
      startChunkApi: filter(startChunkApi, data),
      chunkApi: filter(chunkApi, data),
      finishChunkApi: filter(finishChunkApi, data),
      accept,
      hideUploadButton
    };

    return (
      <Uplader
        key="input"
        {...selectProps}
      />
    );
  }
}
